const { ccclass, property } = cc._decorator;

const DefaultVertexs = [cc.v2(-50, -50), cc.v2(50, -50), cc.v2(-50, 50), cc.v2(50, 50)];

const DefaultIndices = [0, 2, 1, 1, 2, 3];

@ccclass
export default class MeshRender2D extends cc.RenderComponent {
    private _uvs: cc.Vec2[] = [];
    public get uvs(): cc.Vec2[] {
        return this._uvs;
    }
    public set uvs(value: cc.Vec2[]) {
        this.copyArray(value, this._uvs);
        this["setVertsDirty"]();
    }

    private _vertexs: cc.Vec2[] = [];
    public get vertexs(): cc.Vec2[] {
        return this._vertexs;
    }
    public set vertexs(value: cc.Vec2[]) {
        this.copyArray(value, this._vertexs);
        this["setVertsDirty"]();
    }

    private _indices: number[] = [];
    public get indices(): number[] {
        return this._indices;
    }
    public set indices(value: number[]) {
        this.copyArray(value, this._indices);
        this["setVertsDirty"]();
    }

    protected _validateRender() {
        if (!this._vertexs.length || !this._indices.length) {
            this["disableRender"]();
        }
    }

    protected onLoad(): void {
        if (!this._vertexs.length) {
            this.vertexs = DefaultVertexs;
        }

        if (!this._indices.length) {
            this.indices = DefaultIndices;
        }
    }

    private copyArray<T>(from: Array<T>, to: Array<T>) {
        if (to.length !== from.length) {
            to.length = from.length;
        }

        for (let i = 0, len = from.length; i < len; i++) {
            to[i] = from[i];
        }
    }
}
